package cn.parus.dynamicRouter.Filter;

import cn.parus.dynamicRouter.metrics.GatewayMetrics;
import io.micrometer.core.instrument.Timer;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Title: MetricsFilter
 * @Author 黄莲娇
 * @Package com.status.dynamicRouter.filter
 * @Date 2024/4/4 13:51
 * @description: 网关全局过滤器，用于收集请求的监控指标，包括请求计数、响应时间和状态码统计
 * @Version: 1.0
 */

@Component
public class MetricsFilter implements GlobalFilter, Ordered {
    private final GatewayMetrics metrics;

    public MetricsFilter(GatewayMetrics metrics) {
        this.metrics = metrics;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String routeId = exchange.getRequest().getPath().value();
        Timer.Sample sample = metrics.startTimer();

        metrics.recordRequest(routeId);

        return chain.filter(exchange)
                .doFinally(signalType -> {
                    metrics.stopTimer(sample, routeId);
                    // 直接获取状态码数值
                    int statusCode = exchange.getResponse().getStatusCode() != null
                            ? exchange.getResponse().getStatusCode().value()
                            : 500;  // 默认值
                    metrics.recordStatus(routeId, String.valueOf(statusCode));
                });

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
